using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace SuperService
{
	partial class IPLogger : ServiceBase
    {

        private static long timerPeriod = 3600000; //1h
        // Create a timer that waits one second, then invokes every second.
        private static Timer timer = new Timer(new TimerCallback(timer1_Tick), null, timerPeriod, timerPeriod);
     
		public IPLogger()
		{
			InitializeComponent();
   
		}

        private static void timer1_Tick(object sender)
		{
			//LogEvent("This Timer has been ticked!", EventLogEntryType.Information);
            LogEvent("IP is: " + GetExternalIP(), EventLogEntryType.Information);
		}

		protected override void OnStart(string[] args)
        {
           

			LogEvent("IPLogger has started!", EventLogEntryType.Information);
		}

		protected override void OnStop()
		{
            LogEvent("IPLogger has stopped.", EventLogEntryType.Information);
		}

		protected override void OnPause()
		{
			base.OnPause();
            timer.Dispose();
		}

		protected override void OnContinue()
		{
			base.OnContinue();
            timer = new Timer(new TimerCallback(timer1_Tick), null, timerPeriod, timerPeriod);
		}

        public static IPAddress GetExternalIP()
        {
            WebRequest hwr = HttpWebRequest.Create(new Uri("http://checkip.dyndns.org"));
            WebResponse wr = hwr.GetResponse();
            Stream stream = wr.GetResponseStream();
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
            string htmlResult = streamReader.ReadToEnd();
            string[] htmlSplit = htmlResult.Split(new string[] { ":", "<" }, StringSplitOptions.RemoveEmptyEntries);
            string IP = htmlSplit[6].Trim();
            stream.Close();
            wr.Close();
            return IPAddress.Parse(IP);
        }

		static void LogEvent(String Message, EventLogEntryType type)
		{
            StreamWriter streamWriter;
			String source = "IPLogger";
			String log = "Application";
			if (!EventLog.SourceExists(source))
			{
				EventLog.CreateEventSource(source, log);
			}

			EventLog eLog = new EventLog();
			eLog.Source = source;

			eLog.WriteEntry(Message, type);

            if (!File.Exists("C:\\ip_logfile.txt"))
            {
                streamWriter = new StreamWriter("C:\\ip_logfile.txt");
            }
            else
            {
                streamWriter = File.AppendText("C:\\ip_logfile.txt");
            }

            streamWriter.WriteLine("[" + DateTime.Now + "] " + Message);
            streamWriter.Close();
		}
	}
}
